import React from 'react';
import PropTypes from 'prop-types';
import {Layout, message} from 'antd';
import DocumentTitle from 'react-document-title';
import {connect} from 'dva';
import {Redirect, Route, routerRedux, Switch} from 'dva/router';
import {ContainerQuery} from 'react-container-query';
import classNames from 'classnames';
import {enquireScreen, unenquireScreen} from 'enquire-js';
import GlobalHeader from '../components/GlobalHeader';
import SiderMenu from '../components/SiderMenu';
import NotFound from '../routes/Exception/404';
import {getRoutes} from '../utils/utils';
import Authorized from '../utils/Authorized';
import styles from './BasicLayout.less';
import {getFilterMenuData, getMenuData} from '../common/menu';

// import logo from '../assets/treec.png';
import ComponentBase from '../components/Base/ComponentBase';

import {ModalView} from 'antd-extra';
import ModalUserInfo from '../routes/User/ModalUserInfo';
import ModalEditUser from '../routes/employee/modals/ModalEditUser';

const {Content, Header, Footer} = Layout;
const {AuthorizedRoute} = Authorized;

/**
 * 根据菜单取得重定向地址.
 */
const redirectData = [];
const getRedirect = item => {
  if (item && item.children) {
    if (item.children[0] && item.children[0].path) {
      redirectData.push({
        from: `${item.path}`,
        to: `${item.children[0].path}`,
      });
      item.children.forEach(children => {
        getRedirect(children);
      });
    }
  }
};
getMenuData().forEach(getRedirect);

/**
 * 获取面包屑映射
 * @param {Object} menuData 菜单配置
 * @param {Object} routerData 路由配置
 */
// const getBreadcrumbNameMap = (menuData, routerData) => {
//   const result = {};
//   const childResult = {};
//   for (const i of menuData) {
//     if (!routerData[i.path]) {
//       result[i.path] = i;
//     }
//     if (i.children) {
//       Object.assign(childResult, getBreadcrumbNameMap(i.children, routerData));
//     }
//   }
//   return Object.assign({}, routerData, result, childResult);
// };

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};

let isMobile;
enquireScreen(b => {
  isMobile = b;
});

@connect(({user, global = {}, loading}) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  // subMenuOpen: global.subMenuOpen | true,
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
}))
export default class BasicLayout extends ComponentBase {
  static childContextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
  };

  state = {
    isMobile,
  };

  getChildContext() {
    const {location, routerData} = this.props;
    return {
      location,
      // breadcrumbNameMap: getBreadcrumbNameMap(getMenuData(), routerData),
    };
  }

  componentDidMount() {
    this.enquireHandler = enquireScreen(mobile => {
      this.setState({
        isMobile: mobile,
      });
    });
  }

  componentWillUnmount() {
    unenquireScreen(this.enquireHandler);
  }

  handleMenuCollapse = collapsed => {
    const {dispatch} = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };

  handleNoticeClear = type => {
    message.success(`清空了${type}`);
    const {dispatch} = this.props;
    dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
  };

  handleMenuClick = ({key}) => {
    const {dispatch} = this.props;
    if (key === 'triggerError') {
      dispatch(routerRedux.push('/exception/trigger'));
      return;
    }

    /**
     * 修改密码
     */
    if (key === 'password') {
      ModalView.open(ModalEditUser,
        {title: '修改密码', width: '480px'},
        {
          user: this.getLoginInfo(),
          update: true,
          editPassword: true,
          dispatch: this.props.dispatch,
          result: async data => {
            dispatch({
              type: 'user/logout',
            });
            //  const res = await this.props.dispatch(
            //    {type: 'user/updateUser', payload: data},
            //  );
            //  console.log('res', res);
            //  const {status} = res;
            //  if (status === 'ok') {
            //    notify({ message: '修改成功，请重新登录！', type: 'info' });
            //    dispatch({
            //      type: 'user/logout',
            //    });
            //    return;
            //  }
            // this.requestReturn(res)
          },
        },
      );
    }

    /**
     * 个人中心
     */
    if (key === 'user') {
      ModalView.open(ModalUserInfo, {title: '个人中心', width: 1080},
        {
          result: {}
        });
    }

    /**
     * 退出登录
     */
    if (key === 'logout') {
      dispatch({
        type: 'user/logout',
      });
    }
  };

  handleNoticeVisibleChange = visible => {
    const {dispatch} = this.props;
    if (visible) {
      dispatch({
        type: 'global/fetchNotices',
      });
    }
  };
  handleMenuOpen = openKeys => {

  };

  render() {
    const {
      currentUser,
      fetchingNotices,
      notices,
      routerData,
      match,
      location,
      collapsed,
      subMenuOpen,
    } = this.props;
    // console.log('collapsed', collapsed);
    const {isMobile: mb, isFirst = true} = this.state;

    const baseRedirect = 'desktop';
    const layout = (
      <Layout
        style={{position: 'sticky', zIndex: 1, height: '100vh', overflow: 'hidden', width: '100%'}}
      >
        <Header>
          <GlobalHeader
            // logo={logo}
            currentUser={currentUser}
            fetchingNotices={fetchingNotices}
            notices={notices}
            collapsed={collapsed}
            isMobile={mb}
            onNoticeClear={this.handleNoticeClear}
            onCollapse={this.handleMenuCollapse}
            onMenuClick={this.handleMenuClick}
            onNoticeVisibleChange={this.handleNoticeVisibleChange}
          />
        </Header>

        <Layout>
          <SiderMenu
            // 不带Authorized参数的情况下如果没有权限,会强制跳到403界面
            // If you do not have the Authorized parameter
            // you will be forced to jump to the 403 interface without permission
            Authorized={Authorized}
            // menuData={getMenuData()}
            menuData={getFilterMenuData()}
            collapsed={collapsed}
            location={location}
            isMobile={mb}
            onCollapse={this.handleMenuCollapse}
            style={{position: 'sticky', zIndex: 2, height: '95vh'}}
          />
          <Content
            style={{position: 'sticky', zIndex: 5, height: '93vh', marginBottom: 10}}
          >
            <Switch>
              {redirectData.map(item => (
                <Redirect key={item.from} exact from={item.from} to={item.to}/>
              ))}
              {
                getRoutes(match.path, routerData).map(item => (
                  <AuthorizedRoute
                    key={item.key}
                    path={item.path}
                    component={item.component}
                    exact={item.exact}
                    authority={item.authority}
                    redirectPath="/exception/403"
                  />
                ))
              }
              <Redirect exact from="/" to={baseRedirect}/>
              <Route render={NotFound}/>
            </Switch>
          </Content>
        </Layout>
        <Footer className={styles.footer} style={{textAlign: 'center'}}>新蓝化学</Footer>
      </Layout>
    );


    return (
      <DocumentTitle title={this.getTenantName()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
      </DocumentTitle>
    );
  }
}
